﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Main.cs" >
//
// Description:
// Main
//
// This program is free software: you can redistribute it and/or modify
// it under the +terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see http://www.gnu.org/licenses/. 
// </copyright>
// <summary>
// Email: 20392006@qq.com
// </summary>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.Diagnostics;
using System.IO;
using System.Management;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace Str_QrCode
{
    public partial class Main : Form
    {

        #region 检查系统位宽是32or64
        /// <summary>
        /// 检查系统位宽
        /// </summary>
        public static int Arch()
        {
            if (Environment.Is64BitOperatingSystem)
                return 64;
            else
                return 86;
        }
        #endregion

        public static string DIR_PATH = AppDomain.CurrentDomain.BaseDirectory;
        private static string EXE_OA3TOOL = DIR_PATH + "OA3Tool_x" + Arch() + ".exe";
        private string CFG_CHECKUP = DIR_PATH + "checkup.cfg";
        private static string TEMP_BIOSKEY = DIR_PATH + "Bioskey.xml";
        private static string TXT_FILE = DIR_PATH + "qrcode.txt";
        public Main()
        {
            InitializeComponent();
        }

        private void Form_Qr_Load(object sender, EventArgs e)
        {
            if (!File.Exists(TXT_FILE))
            {
                MessageBox.Show(Owner, "No found " + TXT_FILE);
                Application.Exit();
                return;
            }
            this.Show();
            this.Text = "QrCode";
            this.btn_Exit.Text = "Exit";
            
            string MyFile = ReadTxt();

            if (MyFile.Length != 0)
            {
                qrCodeGraphicControl1.Text = MyFile;
                label1.Text = MyFile;
            }
            else
            {
                label1.Text = "The qrcode.txt is empty !";
            }
            
        }

        #region 读取txt文件
        /// <summary>
        /// 读取txt文件
        /// </summary>
        /// <returns>sn/null</returns>
        public string ReadTxt()
        {
            StreamReader str = new StreamReader(TXT_FILE, Encoding.Default);
            string line = str.ReadLine();
            str.Close();
            if (line != null)
            {
                return line;
            }
            return "";
        }
        #endregion

        #region 检查依赖文件
        /// <summary>
        /// 检查依赖文件
        /// </summary>
        private bool CheckFiles()
        {
            if (!File.Exists(EXE_OA3TOOL))
            {
                MessageBox.Show(this, "Missing:" + EXE_OA3TOOL, "SystemInfo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            if (!File.Exists(CFG_CHECKUP))
            {
                MessageBox.Show(this, "Missing:" + CFG_CHECKUP, "SystemInfo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            return true;
        }
        #endregion

        #region 读取系统SN
        /// <summary>
        /// 读取系统SN
        /// </summary>
        /// <returns>sn/null</returns>
        public static string GetSerialNumber()
        {
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from Win32_baseboard");
            string biosNumber = null;
            foreach (ManagementObject mgt in searcher.Get())
            {
                biosNumber = mgt["SerialNumber"].ToString();
            }
            return biosNumber;
        }
        #endregion

        #region 检查BIOS是否现有DPK
        /// <summary>
        /// 检查BIOS是否现有DPK
        /// </summary>
        private string IsExistDPK()
        {
            string resualt = string.Empty;
            if (File.Exists(TEMP_BIOSKEY))
                File.Delete(TEMP_BIOSKEY);
            string[] arg = new string[2];
            arg[0] = "/Report";
            arg[1] = "/ConfigFile=" + CFG_CHECKUP;
            if (StartProcess(EXE_OA3TOOL, arg, "nolog") == 0)
            {
                resualt = ReadXMLNode(TEMP_BIOSKEY, "/Key/ProductKeyID");
                File.Delete(TEMP_BIOSKEY);
                return resualt;
            }
            else
            {
                return resualt;
            }
        }
        #endregion

        #region 调用外部exe
        /// <summary>
        /// 调用外部exe
        /// </summary>
        /// <param exefile="*.exe">调用外部*.exe可执行程序</param>
        /// <param args="string[]">*.exe执行参数</param>
        /// <param str="log">打印Log信息</param>
        /// <returns>int</returns>
        public long StartProcess(string exefile, string[] args, string str)
        {
            long n = -1;
            string parameters = " ";
            foreach (string a in args)
            {
                parameters = parameters + a + " ";
            }
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.FileName = exefile;
            startInfo.Arguments = parameters;
            startInfo.CreateNoWindow = true;
            startInfo.UseShellExecute = false;
            //startInfo.RedirectStandardInput = true;
            startInfo.RedirectStandardOutput = true;
            //startInfo.Verb = "RunAs";
            Process p = new Process();
            p.StartInfo = startInfo;
            try
            {
                p.Start();
                p.WaitForExit(180000);//等待外部程序执行时间为3分钟
                if (p.HasExited == false)
                {
                    try
                    {
                        p.Kill(); //超时，杀死进程
                    }
                    catch{}
                }
                string result = p.StandardOutput.ReadToEnd();
                n = p.ExitCode;
                p.Close();
                return n;

            }
            catch (Exception)
            {
                if (p != null)
                    p.Close();
                return n;
            }
        }
        #endregion

        #region 读取xml文件下的节点
        /// <summary>
        /// 读取xml文件下的节点
        /// </summary>
        /// <param _xmlPath="..\*.xml">xml文件路径</param>
        /// <param _xmlNode="string">要读取的xml文件节点</param>
        /// <returns>节点或是节点属性内容</returns>
        public string ReadXMLNode(string _xmlPath, string _xmlNode)
        {
            XmlDocument xmlDoc = new XmlDocument();
            try
            {
                xmlDoc.Load(_xmlPath);
                XmlNode itemCode = xmlDoc.SelectSingleNode(_xmlNode);
                if (itemCode != null)
                {
                    //判断节点是否有属性值
                    if (itemCode.Attributes.Count > 0)
                    {
                        return itemCode.Attributes["value"].Value; //取节点属性的值
                    }
                    else
                    {
                        return itemCode.InnerText;
                    }
                }

                return null;
            }
            catch (Exception)
            {
                return null;
            }
        }
        #endregion

        private void btn_Exit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        
    }
}
